/**
 * Auto Send SMS Program
 * Write By Punan 2013.2.17
 */


package com.huaqin.punan.autosms;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity {

	public static final String TAG = "AutoSendSMSMain";
	public static final String PREFERENCES_AUTO_SENDSMS = "PreferencesAutoDialer";
	public static final String ACTION_SMS_SEND = "com.huaqin.punan.autosms";
	public static final int REDSEND_ON_EVERY_ONE_SECOND = 0;
	public static final int REDSEND_ON_EVERY_FIVE_SECOND = 1;
	public static final int REDSEND_ON_EVERY_TEN_SECOND = 2;
	private static final int CONTACT_PICKER_RESULT = 1002;
	
	private RadioGroup mRadioGroup;
	private RadioButton mRadioButton1;
	private RadioButton mRadioButton2;
	private RadioButton mRadioButton3;
	private EditText mTextMsg;
	private EditText mPhoneNum;
	private ImageButton mImageButton;
	private Button mButton;
	private Spinner mSpinner;
	
	private boolean startflag = false;
	public static int reSendType = 0 ;
	public static int reSendTimes = 10;
	public static String textMsg = "";
	public static String contactName = "";
	public static String phoneNum = "";
	private boolean debugFlag = true;
	
	SharedPreferences mReSendSMSPreference;
	TelephonyManager mTelephonyManager;
	BroadcastReceiver SmsBroadcastReceiver;
	Timer timer;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mReSendSMSPreference = getSharedPreferences(PREFERENCES_AUTO_SENDSMS,Context.MODE_PRIVATE);
		final SharedPreferences.Editor editor = mReSendSMSPreference.edit();

		mRadioGroup = (RadioGroup)findViewById(R.id.myradiogroup);
		mRadioButton1 = (RadioButton)findViewById(R.id.radiobtn1);
		mRadioButton2 = (RadioButton)findViewById(R.id.radiobtn2);
		mRadioButton3 = (RadioButton)findViewById(R.id.radiobtn3);
		mTextMsg = (EditText)findViewById(R.id.et_msg);
		mPhoneNum = (EditText)findViewById(R.id.et_num);
		mImageButton = (ImageButton)findViewById(R.id.ib_addnum);
		mButton = (Button)findViewById(R.id.btn_send);
		mSpinner = (Spinner)findViewById(R.id.sp_times);
		
		reSendType = mReSendSMSPreference.getInt("auto_resend_type", 0);
		textMsg = mReSendSMSPreference.getString("auto_resend_msg", "");
		phoneNum = mReSendSMSPreference.getString("auto_resend_num", "");
		reSendTimes = mReSendSMSPreference.getInt("auto_resend_times", 10);
		
		if(reSendType == 0){
			mRadioButton1.setChecked(true);
		}else if(reSendType == 1){
			mRadioButton2.setChecked(true);
		}else if(reSendType == 2){
			mRadioButton3.setChecked(true);
		}
		
		if(textMsg != null && !("".equals(textMsg))){
			mTextMsg.setText(textMsg);
		}
		
		if(phoneNum != null && !("".equals(phoneNum))){
			mPhoneNum.setText(phoneNum);
		}
		
		if(debugFlag)
			Log.i(TAG, "reSendType="+reSendType+",textMsg="+textMsg+",phoneNum="+phoneNum);
		
		
		SmsBroadcastReceiver = new BroadcastReceiver(){
			@Override
			public void onReceive(Context context, Intent intent) {
				// TODO Auto-generated method stub
				String message = null;
				boolean error = true;
				switch(getResultCode()){
				case Activity.RESULT_OK:
					message = "Message Send Success";
					error = false;
					break;
				case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
					message = "Error: generic failure";
					break;
				case SmsManager.RESULT_ERROR_NO_SERVICE:
					message = "Error: no service";
					break;
				case SmsManager.RESULT_ERROR_NULL_PDU:
					message = "Error: null pdu";
					break;
				case SmsManager.RESULT_ERROR_RADIO_OFF:
					message = "Error: radio off";
					break;
				}
				
				if(!error){
					if(debugFlag) Log.i(TAG, message);
					
				}else{
					if(debugFlag) Log.i(TAG, message);
					
				}
			}
		};
		
		//mSpinner.
		mSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				switch(arg2){
				case 0:
					reSendTimes = 10;
					break;
				case 1:
					reSendTimes = 20;
					break;
				case 2:
					reSendTimes = 30;
					break;
				case 3:
					reSendTimes = 50;
					break;
				case 4:
					reSendTimes = 100;
					break;
				default:
					reSendTimes = 10;
				}
				
				//editor.putInt("auto_resend_times", reSendTimes);
				//editor.commit();
				
				if(debugFlag)
					Log.i(TAG, "Spinner reSendTimes=="+reSendTimes);

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				if(debugFlag)
					Log.i(TAG, "Spinner nothing selected");
			}});
		
		mRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener(){

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// TODO Auto-generated method stub
				switch(checkedId){
				case R.id.radiobtn1:
					reSendType = REDSEND_ON_EVERY_ONE_SECOND;
					break;
				case R.id.radiobtn2:
					reSendType = REDSEND_ON_EVERY_FIVE_SECOND;
					break;
				case R.id.radiobtn3:
					reSendType = REDSEND_ON_EVERY_TEN_SECOND;
					break;
				default:
					reSendType = REDSEND_ON_EVERY_ONE_SECOND;
					break;
				}
				
				editor.putInt("auto_resend_type", reSendType);
				editor.commit();
				
				if(debugFlag)
					Log.i(TAG, "RadioGroup reSendType="+reSendType);
			}});
		
		mButton.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				textMsg = mTextMsg.getText().toString();
				phoneNum = mPhoneNum.getText().toString().trim();
				
				editor.putString("auto_resend_msg", textMsg);
				editor.putString("auto_resend_num", phoneNum);
				editor.commit();
				
				if(!startflag){
					
					if("".equals(phoneNum) || phoneNum == null){
						
						Toast.makeText(MainActivity.this, "请输入电话号码", Toast.LENGTH_SHORT).show();
					}else if("".equals(textMsg) || textMsg == null){
						
						Toast.makeText(MainActivity.this, "请输入信息", Toast.LENGTH_SHORT).show();
					}else{
						startflag = true;
						
						registerReceiver(SmsBroadcastReceiver, new IntentFilter(ACTION_SMS_SEND));
						
						timer = new Timer();
						timer.schedule(new TimerTask(){
							
							int tem_times = reSendTimes;
							
							@Override
							public void run() {
								// TODO Auto-generated method stub
								tem_times--;
								if(tem_times == 0){
									timer.cancel();
									startflag = false;
									//UpdateButtonState();
									//12-31 23:14:54.593: E/AndroidRuntime(3619): android.view.ViewRootImpl$CalledFromWrongThreadException: 
									//Only the original thread that created a view hierarchy can touch its views.
									
									/*method one: 
									runOnUiThread(new Runnable(){
										public void run(){
											
										}
									});*/
									
									//method two:
									Message msg = new Message();
									String text_tmp = "text";
									msg.obj = text_tmp;
									mHandler.sendMessage(msg);
									
								}
								
								SendSMS(textMsg,phoneNum);
								
							}}, 1000, 1000*(1+5*reSendType));
						
						mButton.setText(R.string.btn_name_stop);
					}
					
				}else{
					
					startflag = false;
					
					RemoveBroadcastReceiver();
					
					if(timer != null){
						timer.cancel();
					}
					
					mButton.setText(R.string.btn_name_start);
				}
			}});
		
		mImageButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,	ContactsContract.Contacts.CONTENT_URI);
				startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
			}});
	}
	
	private void SendSMS(String msg, String num){
		if(debugFlag)
			Log.i(TAG, "SendSMS has been called");

		SmsManager mSmsManager = SmsManager.getDefault();
		List<String> messages = mSmsManager.divideMessage(msg);
		
		String recipient = num;
		for(String message : messages){
			mSmsManager.sendTextMessage(recipient, 	//String destinationAddress
					null, 							//String scAddress
					message, 						//String text
					PendingIntent.getBroadcast(MainActivity.this, 0, new Intent(ACTION_SMS_SEND), 0), //PendingIntent sentIntent
					null);							//PendingIntent deliveryIntent
		}
	}

	private void RemoveBroadcastReceiver(){
		unregisterReceiver(SmsBroadcastReceiver);
	}
	
	Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			mButton.setText(R.string.btn_name_start);
			//mButton.setText((String)msg.obj);
		}
	};
	
	private void UpdateButtonState(){
		mButton.setText(R.string.btn_name_start);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch(requestCode){
		case CONTACT_PICKER_RESULT :
			if(resultCode == Activity.RESULT_OK){
        		Uri contactData = data.getData();
 				Cursor cursor = getContentResolver().query(contactData, null, null, null, null);
 				while(cursor.moveToNext()){
 					String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
 			        contactName = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
 			        String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
 			        
 			        if ( hasPhone.equalsIgnoreCase("1"))
 			            hasPhone = "true";
 			        else
 			            hasPhone = "false" ;
 			       
 			        if (Boolean.parseBoolean(hasPhone)){
 			        	Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
 			        	while (phones.moveToNext()){
 			        		phoneNum = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
 			        	}
 			        phones.close();
 			        }
 				}
			break;
			}
		}
		Log.i(TAG, "Result_name="+contactName);
		Log.i(TAG, "Result_num="+phoneNum);
		mPhoneNum.setText(phoneNum);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		RemoveBroadcastReceiver();
	}
}
